package com.mlamp.nanchang.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.mlamp.nanchang.entity.FaceWarning;
import com.mlamp.nanchang.entity.QueryAlarmRecordsWithPageRequest;
import com.mlamp.nanchang.hikvision.HkArtemisConfig;
import com.mlamp.nanchang.hikvision.HkArtemisHttpUtil;
import com.mlamp.nanchang.mapper.BigDataBkryyjMapper;

//人脸预警
@Service
public class FaceWarningService {
	private static final Logger log = LoggerFactory.getLogger(FaceWarningService.class);
	@Autowired
	private BigDataBkryyjMapper bigDataBkryyjMapper;
	
	private static String ARTEMIS_PATH = "/artemis";
	private static final HkArtemisHttpUtil artemisHttpUtil = new HkArtemisHttpUtil(new HkArtemisConfig("10.137.21.24", "20989624", "pbctiWR4faouT8r9QkHV"));

	private String queryAlarmRecordsWithPage(QueryAlarmRecordsWithPageRequest queryAlarmRecordsWithPageRequest ){
		String queryAlarmRecordsWithPageDataApi = ARTEMIS_PATH +"/api/aiapplication/v1/face/queryAlarmRecordsWithPage";
		Map<String,String> path = new HashMap<String, String>(2){
			{
				put("https://",queryAlarmRecordsWithPageDataApi);
			}
		};
		String body=JSON.toJSONString(queryAlarmRecordsWithPageRequest);
		String result = artemisHttpUtil.doPostStringArtemis(path,body,null,null,"application/json");
		log.debug("接口请求结果: {}", result);
		return result;
	}
	
	/**
	 * 分页查询预警信息，
	 * @param pageNo
	 * @param pageSize
	 * @param starttime
	 * @param endtime
	 * @return
	 */
	public Page<FaceWarning> pagingFaceWarning(int pageNo, int pageSize, String starttime, String endtime){
		Page<FaceWarning> page = new Page<>(pageNo, pageSize);
        QueryAlarmRecordsWithPageRequest request=new QueryAlarmRecordsWithPageRequest();
        request.setPageNo(pageNo);
        request.setPageSize(pageSize);
        request.setBeginTime(starttime);
        request.setEndTime(endtime);
        JSONObject json = (JSONObject) JSON.parse(queryAlarmRecordsWithPage(request));
        String code = json.getString("code");
        if("0".equals(code)) {
        	//成功
        	JSONObject data = json.getJSONObject("data");
        	JSONArray list = data.getJSONArray("list");
        	List<FaceWarning> faceWarnings = this.transformData(list);
        	page.setTotal(data.getLongValue("total"));
        	page.setRecords(faceWarnings);
        	return page;
        } else {
        	//失败
        	return null;
        }
    }
	
	private void saveFaceWaning(List<FaceWarning> list) {
		for (FaceWarning e : list) {
			bigDataBkryyjMapper.deleteByAlarmId(e.getBjuuid());
			bigDataBkryyjMapper.insert(e);
		}
	}
	
	@Transactional
	public void saveFaceWarning(List<FaceWarning> faceWarnings) {
		saveFaceWaning(faceWarnings);
	}
	
	public List<FaceWarning> transformData(JSONArray array) {
		List<FaceWarning> faceWanings = new ArrayList<>();
		for (Object object : array) {
			JSONObject json = (JSONObject) object;
			FaceWarning fw = new FaceWarning();
			fw.setId(UUID.randomUUID().toString());
			
			//布控信息
			fw.setIndexcode(json.getString("cameraIndexCode"));
			fw.setBkrw(json.getString("name"));
			fw.setBkrwid(json.getString("taskId"));
			fw.setJd(json.getString("latitude"));
			fw.setWd(json.getString("longitude"));
			try {
				fw.setBjsj(DateUtils.parseDate(json.getString("alarmTime"), "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"));
			} catch (ParseException e) {
				log.error("预警时间解析错误", e);
			}
			fw.setBjuuid(json.getString("alarmId"));
			
			//预警信息
			fw.setDbt(transformPicUrl(json.getString("refrencePicUrl")));
			fw.setXm(json.getString("personName"));
			fw.setSsmdk(json.getString("personLibName"));
			fw.setZjhm(json.getString("certificateNumber"));
			fw.setZpzp(transformPicUrl(json.getString("snappedPicUrl")));
			fw.setXsd(json.getString("similarity"));
			fw.setBjdd(json.getString("cameraName"));


			//没有的属性
			fw.setSsqy("");
			fw.setBjybh("");
			fw.setBjylx("");

			fw.setBjtp("");
			fw.setSfgz("");
			
			faceWanings.add(fw);
		}
		return faceWanings;
	}
	
	private String transformPicUrl(String url) {
		String base64 = Base64.getEncoder().encodeToString(url.getBytes());
		return String.format("http://%s/ngx/proxy?i=%s", "10.137.21.24", base64);
	}
}
